﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg.Loquacious;
using FluentNHibernate.Automapping;

namespace Mecanica.Repositório
{
    public class SessionHelper
    {

        private NHibernate.ISessionFactory _SessionFactory;
        private NHibernate.ISession _Session;
        private static SessionHelper _SessionHelper;

        private SessionHelper()
        {
            NHibernate.Cfg.Configuration configuracao = new NHibernate.Cfg.Configuration();
            configuracao.DataBaseIntegration(x =>
            {
                x.ConnectionStringName = "conexaoPostgres";
                x.Dialect<NHibernate.Dialect.PostgreSQL82Dialect>();
                x.Driver<NHibernate.Driver.NpgsqlDriver>();
                x.LogFormatedSql = true;
                x.LogSqlInConsole = true;
            })
            .Proxy(x=>x.ProxyFactoryFactory<NHibernate.ByteCode.Castle.ProxyFactoryFactory>());
                        
            var cfg = FluentNHibernate.Cfg.Fluently.Configure(configuracao).Mappings  (x =>
                  x.AutoMappings.Add(AutoMap.AssemblyOf<Dominio.Entidades.Core.Usuario>()));

            configuracao = cfg.BuildConfiguration();

            _SessionFactory = configuracao.BuildSessionFactory();

            NHibernate.Tool.hbm2ddl.SchemaExport export = new NHibernate.Tool.hbm2ddl.SchemaExport(configuracao);
            export.Execute(true,true, false);
        }

        public static SessionHelper getInstance()
        {
            if (_SessionHelper == null)
                _SessionHelper = new SessionHelper();
            return _SessionHelper;
        }

        public NHibernate.ISession GetSession()
        {
            if (_Session == null)
                _Session = _SessionFactory.OpenSession();
            return _Session;
        }
    }
}
